import os
import process
from spass.core import warehouse

def visit(script_name, test_dir, target_dir, id_assignment, id_team, id_version):
    oldpwd = os.getcwd()
    os.chdir(test_dir)
    _visit(script_name, test_dir, target_dir, id_assignment, id_team, id_version)
    os.chdir(oldpwd)
    
def _visit(script_name, curdir, target_dir, id_assignment, id_team, id_version):
    lsd = os.listdir(curdir)
    lsd.sort()
    for i in lsd:
        module = os.path.splitext(i)
        if module[1] == ".py" and not module[0] == "__init__":
            ret, stdout = process.run(module[0], target_dir)
            warehouse.core_w_write_test_log(id_assignment, id_team, id_version, script_name + '.' + module[0], str(stdout))
            
            nextdir = curdir + '/' + module[0] + ".d"
            if ret == 0 and os.path.isdir(nextdir):
                os.chdir(nextdir)
                _visit(script_name, nextdir, target_dir, id_assignment, id_team, id_version)
                os.chdir(curdir)
